/*
 * Android SDK for Matomo
 *
 * @link https://github.com/matomo-org/matomo-android-sdk
 * @license https://github.com/matomo-org/matomo-sdk-android/blob/master/LICENSE BSD-3 Clause
 */

package com.org.matomo.demo;

import com.org.matomo.demo.button.RTextView;
import com.org.matomo.demo.util.StrUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.*;
import ohos.agp.window.service.WindowManager;
import ohos.hiviewdfx.HiLog;
import ohos.multimodalinput.event.TouchEvent;
import org.matomo.sdk.Logger;
import org.matomo.sdk.QueryParams;
import org.matomo.sdk.TrackMe;
import org.matomo.sdk.Tracker;
import org.matomo.sdk.extra.EcommerceItems;
import org.matomo.sdk.extra.TrackHelper;

import java.security.SecureRandom;
import java.util.*;

public class DemoAbilitySlice extends AbilitySlice {
    int cartItems = 0;
    private EcommerceItems items;
    private Text txtReportedData;
    private Image spinner;
    private DirectionalLayout refreshLayout;
    private RTextView[] buttons;
    private TextField idGoalTextEditView;

    private Tracker getTracker() {
        return ((MyApplication) getAbility().getAbilityPackage()).getTracker();
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        int titleColor = -13615201;
        WindowManager.getInstance().getTopWindow().get().setStatusBarColor(titleColor);
        getWindow().setInputPanelDisplayType(WindowManager.LayoutConfig.INPUT_ADJUST_PAN);
        super.setUIContent(ResourceTable.Layout_ability_demo);
        getTracker().addTrackingCallback(trackMe -> {
            Map<String, String> queryParams = trackMe.getmQueryParams();
            StringBuilder builder = new StringBuilder();
            builder.append("{").append(" ");
            for (Map.Entry<String, String> entry : queryParams.entrySet()) {
                builder.append(entry.getKey()).append(":").append(entry.getValue()).append(" ");
                HiLog.info(Logger.LABEL, "" + entry.getKey() + "<>" + entry.getValue());
                System.out.print(">>>>>>>>>>>>" + entry.getKey() + "<>" + entry.getValue());
            }
            builder.append("}");
            return trackMe;
        });
        initView();
    }

    DirectionalLayout directionalLayout;
    private boolean isTop = false;

    private void initView() {
        directionalLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_dir_all);
        directionalLayout.setClickedListener(component ->
                setIcMoreHide());
        refreshLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_title_settings);
        refreshLayout.setVisibility(Component.HIDE);
        refreshLayout.setClickedListener(component -> {
            Intent secondIntent = new Intent();
//                 指定待启动FA的bundleName和abilityName
            Operation operation = new Intent.OperationBuilder()
                    .withDeviceId("")
                    .withBundleName("com.org.matomo.demo")
                    .withAbilityName("com.org.matomo.demo.SettingAblilty")
                    .build();
            secondIntent.setOperation(operation);
            // 通过AbilitySlice的startAbility接口实现启动另一个页面
            startAbility(secondIntent);
            setIcMoreHide();
        });
        txtReportedData = (Text) findComponentById(ResourceTable.Id_txt_reported_data);
        TextField goalTextEditView = (TextField) findComponentById(ResourceTable.Id_goalTextEditView);
        goalTextEditView.setTextInputType(InputAttribute.PATTERN_NUMBER);
        goalTextEditView.setTouchEventListener(new Component.TouchEventListener() {
            @Override
            public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                return false;
            }
        });

        // 动效
        AnimatorValue animatorValue = new AnimatorValue();
        animatorValue.setDuration(500);
        animatorValue.setCurveType(7);
        animatorValue.setStateChangedListener(new Animator.StateChangedListener() {
            @Override
            public void onStart(Animator animator) {
                refreshLayout.setVisibility(Component.VISIBLE);
                setButtonNoClick();
            }

            @Override
            public void onStop(Animator animator) {

            }

            @Override
            public void onCancel(Animator animator) {

            }

            @Override
            public void onEnd(Animator animator) {
            }

            @Override
            public void onPause(Animator animator) {

            }

            @Override
            public void onResume(Animator animator) {

            }
        });
        animatorValue.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
            @Override
            public void onUpdate(AnimatorValue animatorValue, float v) {

            }
        });

        spinner = (Image) findComponentById(ResourceTable.Id_main_spinner);
        spinner.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                animatorValue.start();
            }
        });

        items = new EcommerceItems();
        RTextView trackMainScreenViewButton = (RTextView) findComponentById(ResourceTable.Id_trackMainScreenViewButton);
        trackMainScreenViewButton.setClickedListener(component -> {
            setStrEmpty();
            setIcMoreHide();
            TrackHelper.track(new TrackMe().set(QueryParams.SESSION_START, 1))
                    .screen("/")
                    .title("Main screen")
                    .with(getTracker());
        });

        RTextView trackDispatchNow = (RTextView) findComponentById(ResourceTable.Id_trackDispatchNow);
        trackDispatchNow.setClickedListener(component -> {
            setStrEmpty();
            setIcMoreHide();
            getTracker().dispatch();
        });

        RTextView trackCustomVarsButton = (RTextView) findComponentById(ResourceTable.Id_trackCustomVarsButton);
        trackCustomVarsButton.setClickedListener(component -> {
            setStrEmpty();
            setIcMoreHide();
            TrackHelper.track()
                    .screen("/custom_vars")
                    .title("Custom Vars")
                    .variable(1, "first", "var")
                    .variable(2, "second", "long value")
                    .with(getTracker());
        });

        RTextView raiseExceptionButton = (RTextView) findComponentById(ResourceTable.Id_raiseExceptionButton);
        raiseExceptionButton.setClickedListener(component -> {
            setStrEmpty();
            setIcMoreHide();
            TrackHelper.track()
                    .exception(new Exception("OnPurposeException"))
                    .description("Crash button")
                    .fatal(false)
                    .with(getTracker());
        });

        idGoalTextEditView = (TextField) findComponentById(ResourceTable.Id_goalTextEditView);
        idGoalTextEditView.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String s, int i, int i1, int i2) {
                if (s != null && s.length() > 0 && !StrUtil.isNumeric(s)) {
                    idGoalTextEditView.setText(s.substring(0, s.length() - 1));
                }
            }
        });

        RTextView trackGoalButton = (RTextView) findComponentById(ResourceTable.Id_trackGoalButton);
        trackGoalButton.setClickedListener(component -> {
            setStrEmpty();
            setIcMoreHide();
            float revenue;
            try {
                revenue = Float.parseFloat(((TextField) findComponentById(ResourceTable.Id_goalTextEditView)).getText());
            } catch (Exception e) {
                TrackHelper.track().exception(e).description("wrong revenue").with(getTracker());
                revenue = 0;
            }
            TrackHelper.track().goal(1).revenue(revenue).with(getTracker());
        });

        RTextView addEcommerceItemButton = (RTextView) findComponentById(ResourceTable.Id_addEcommerceItemButton);
        addEcommerceItemButton.setClickedListener(component -> {
            setStrEmpty();
            setIcMoreHide();
            List<String> skus = Arrays.asList("00001", "00002", "00003", "00004");
            List<String> names = Arrays.asList("Silly Putty", "Fishing Rod", "Rubber Boots", "Cool Ranch Doritos");
            List<String> categories = Arrays.asList("Toys & Games", "Hunting & Fishing", "Footwear", "Grocery");
            List<Integer> prices = Arrays.asList(449, 3495, 2450, 250);

            int index = cartItems % 4;
            int quantity = (cartItems / 4) + 1;

            items.addItem(new EcommerceItems.Item(skus.get(index))
                    .name(names.get(index))
                    .category(categories.get(index))
                    .price(prices.get(index))
                    .quantity(quantity));
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < cartItems % 4 + 1; i++) {
                stringBuilder.append(skus.get(i)).append(names.get(i)).append(categories.get(i)).append(prices.get(i));
            }
            cartItems++;
        });

        RTextView trackEcommerceCartUpdateButton = (RTextView) findComponentById(ResourceTable.Id_trackEcommerceCartUpdateButton);
        trackEcommerceCartUpdateButton.setClickedListener(component -> {
            setStrEmpty();
            setIcMoreHide();
            TrackHelper.track()
                    .cartUpdate(8600)
                    .items(items)
                    .with(getTracker());
        });

        RTextView completeEcommerceOrderButton = (RTextView) findComponentById(ResourceTable.Id_completeEcommerceOrderButton);
        completeEcommerceOrderButton.setClickedListener(component -> {
            setStrEmpty();
            setIcMoreHide();
            SecureRandom random = new SecureRandom();
            TrackHelper.track()
                    .order(String.valueOf(10000 * random.nextDouble()), 10000)
                    .subTotal(1000)
                    .tax(2000)
                    .shipping(3000)
                    .discount(500)
                    .items(items)
                    .with(getTracker());
        });
        buttons = new RTextView[]{trackMainScreenViewButton, trackDispatchNow, trackCustomVarsButton,
                raiseExceptionButton, trackGoalButton, addEcommerceItemButton, trackEcommerceCartUpdateButton,
                completeEcommerceOrderButton};
    }

    private void setStrEmpty() {
        txtReportedData.setText("");
    }

    @Override
    protected void onBackground() {
        setIcMoreHide();
        super.onBackground();
    }

    private void setIcMoreHide() {
        if (refreshLayout.getVisibility() == Component.VISIBLE) {
            refreshLayout.setVisibility(Component.HIDE);
            setButtonClick();
        }
    }

    private void setButtonNoClick() {
        for (RTextView button : buttons) {
            button.setClickable(false);
            button.setEnabled(false);
        }
        idGoalTextEditView.setEnabled(false);
        idGoalTextEditView.setClickable(false);
    }

    private void setButtonClick() {
        for (RTextView button : buttons) {
            button.setClickable(true);
            button.setEnabled(true);
        }
        idGoalTextEditView.setEnabled(true);
        idGoalTextEditView.setClickable(true);
    }
}
